﻿using LineOfBusiness.Controls.Base;
using LineOfBusiness.Core.Helper;
using LineOfBusiness.Poco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace LineOfBusiness.AD.Controllers
{
    public class UserPermissionController : LOBController
    {
        public UserPermissionController()
        {
            this.FormName = "tblUserPermission";
        }

        public ActionResult Index()
        {
            return View();
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public JsonResult FunctionList(string id)
        {
            var functions = CacheHelper.FunctionList.Values.Where(x => (string.IsNullOrEmpty(id) ? x.FunctionType == "M" : (x.FunctionType != "M" && x.ParentID==id)) && x.IsActive == true).OrderBy(o => o.Sorting).ToList();

            var fs = from e in functions
                     select new
                     {
                         imageUrl = string.IsNullOrEmpty(e.SmallIcon) ? null : HtmlExtensions.GetBaseUrl + "Content/default/" + e.SmallIcon,
                         id = e.FunctionID,
                         Name = e.CustomName,
                         hasChildren = string.IsNullOrEmpty(id) || CacheHelper.FunctionList.Values.Where(x => x.FunctionType != "M" && x.IsActive == true && x.ParentID == e.FunctionID).Any(),
                         urlFunction = string.IsNullOrEmpty(e.Url) ? "" : HtmlExtensions.GetBaseUrl + e.Url,
                         displayMode = e.DisplayMode,
                         width = e.Width,
                         height = e.Height,
                         CustomName = e.CustomName,
                         permission = new AD_tblUserPermission[]
                         {
                            new AD_tblUserPermission(){ FType="1" },
                            new AD_tblUserPermission(){ FType="2" }
                         }
                     };

            return Json(fs, JsonRequestBehavior.AllowGet);
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public JsonResult GetPermission(string user, string function)
        {
            using (LineOfBusiness.DataAccess.EFDALContainer dal = new LineOfBusiness.DataAccess.EFDALContainer())
            {
                var permis = GetPermission(dal, user, function);
                return Json(permis.ToArray(), JsonRequestBehavior.AllowGet);
            }
            
        }

        private List<AD_tblUserPermission> GetPermission(LineOfBusiness.DataAccess.EFDALContainer dal, string userID, string function)
        {
            var pers = dal.Repository.Get<AD_tblUserPermission>(o => o.FunctionID == function && o.UserGroupID == userID).ToList();
            var def = getDefault(dal,function, userID);

            foreach (var d in def)
            {
                bool isExist = false;
                foreach (var p in pers)
                {
                    if (p.FType == d.FType)
                    {
                        isExist = true;
                        break;
                    }
                }

                if (!isExist)
                {
                    pers.Add(d);
                }
            }

            return pers;
        }

        private List<AD_tblUserPermission> getDefault(LineOfBusiness.DataAccess.EFDALContainer dal,string functionID, string userid)
        {
            List<AD_tblUserPermission> def = new List<AD_tblUserPermission>();
            var function = dal.Repository.GetOne<SYS_FunctionList>(o => o.FunctionID == functionID);

            if (!dal.Repository.GetQuery<SYS_FunctionList>().Where(o => o.ParentID == function.FunctionID).Any())
            {
                def.Add(new AD_tblUserPermission() { FunctionID = functionID, UserGroupID = userid, FType = "1" });

                if (function.DisplayMode != "1")
                {
                    def.Add(new AD_tblUserPermission() { FunctionID = functionID, UserGroupID = userid, FType = "2" });
                    def.Add(new AD_tblUserPermission() { FunctionID = functionID, UserGroupID = userid, FType = "3" });
                    def.Add(new AD_tblUserPermission() { FunctionID = functionID, UserGroupID = userid, FType = "4" });
                }

                switch (function.FunctionID)
                {
                    case "CSST01":
                    case "CSST02":
                    case "CSST03":
                    case "CSST04":
                    case "GLST01":
                    case "IVST01":
                    case "IVST02":
                    case "PPST01":
                    case "SRST01":
                        def.Add(new AD_tblUserPermission() { FunctionID = functionID, UserGroupID = userid, FType = "5" });
                        def.Add(new AD_tblUserPermission() { FunctionID = functionID, UserGroupID = userid, FType = "6" });
                        break;
                    default:
                        break;
                }
            }
            return def;
        }

        [HttpPost]
        public JsonResult SavePermission(List<AD_tblUserPermission> pers)
        {
            using (LineOfBusiness.DataAccess.EFDALContainer dal = new LineOfBusiness.DataAccess.EFDALContainer())
            {
                foreach (var item in pers)
                {
                    dal.Repository.AddOrUpdate(item);
                }

                dal.UnitOfWork.SaveChanges();
                return Json("");
            }
        }

        public JsonResult RemoveAllPermission(string UserID, string Module)
        {
            using (LineOfBusiness.DataAccess.EFDALContainer dal = new LineOfBusiness.DataAccess.EFDALContainer())
            {
                SetOrRemovePers(dal, UserID, Module, false);
                dal.UnitOfWork.SaveChanges();
                return Json("");
            }
        }

        public JsonResult SetAllPermission(string UserID, string Module)
        {
            using (LineOfBusiness.DataAccess.EFDALContainer dal = new LineOfBusiness.DataAccess.EFDALContainer())
            {
                SetOrRemovePers(dal, UserID, Module, true);
                dal.UnitOfWork.SaveChanges();
                return Json("");
            }
        }

        private void SetOrRemovePers(LineOfBusiness.DataAccess.EFDALContainer dal,string UserID, string module, bool IsSet)
        {
            List<AD_tblUserPermission> def = new List<AD_tblUserPermission>();
            var function = dal.Repository.GetQuery<SYS_FunctionList>().Where(o => o.Module == module).ToList();
            var pers = dal.Repository.GetQuery<AD_tblUserPermission>().Where(o => o.UserGroupID == UserID).ToList();

            foreach (var item in function)
            {
                var exist = pers.Where(o => o.FunctionID == item.FunctionID).ToList();
                if (exist.Count > 0)
                {
                    foreach (var i in exist)
                    {
                        i.FIsActive = IsSet;
                        dal.Repository.Update(i);
                    }
                }
                else
                {
                    if (!function.Where(o => o.ParentID == item.FunctionID).Any())
                    {
                        dal.Repository.Add(new AD_tblUserPermission() { FunctionID = item.FunctionID, UserGroupID = UserID, FType = "1", FIsActive = IsSet });

                        if (item.DisplayMode != "1")
                        {
                            dal.Repository.Add(new AD_tblUserPermission() { FunctionID = item.FunctionID, UserGroupID = UserID, FType = "2", FIsActive = IsSet });
                            dal.Repository.Add(new AD_tblUserPermission() { FunctionID = item.FunctionID, UserGroupID = UserID, FType = "3", FIsActive = IsSet });
                            dal.Repository.Add(new AD_tblUserPermission() { FunctionID = item.FunctionID, UserGroupID = UserID, FType = "4", FIsActive = IsSet });
                        }

                        switch (item.FunctionID)
                        {
                            case "CSST01":
                            case "CSST02":
                            case "CSST03":
                            case "CSST04":
                            case "GLST01":
                            case "IVST01":
                            case "IVST02":
                            case "PPST01":
                            case "SRST01":
                                dal.Repository.Add(new AD_tblUserPermission() { FunctionID = item.FunctionID, UserGroupID = UserID, FType = "5", FIsActive = IsSet });
                                dal.Repository.Add(new AD_tblUserPermission() { FunctionID = item.FunctionID, UserGroupID = UserID, FType = "6", FIsActive = IsSet });
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }
        public ActionResult CopyPermision(string UserID, string IsUser)
        {
            ViewBag.UserGroupID = UserID;
            ViewBag.IsUser = IsUser;
            return View();
        }

        public JsonResult Copy(string FromUserID, string ToUserID)
        {
            using (LineOfBusiness.DataAccess.EFDALContainer dal = new LineOfBusiness.DataAccess.EFDALContainer())
            {
                CopyPermission(dal, FromUserID, ToUserID);
                dal.UnitOfWork.SaveChanges();
                return Json("");
            }
        }
        public void CopyPermission(LineOfBusiness.DataAccess.EFDALContainer dal, string FromuserID, string ToserID)
        {
            var f = dal.Repository.Get<AD_tblUserPermission>(o => o.UserGroupID == FromuserID).ToList();
            var t = dal.Repository.Get<AD_tblUserPermission>(o => o.UserGroupID == ToserID).ToList();

            foreach (var item in f)
            {
                var e = t.Where(o => o.FunctionID == item.FunctionID && o.FType == item.FType).FirstOrDefault();
                if (e != null)
                {
                    e.FIsActive = item.FIsActive;
                    dal.Repository.Update(e);
                }
                else
                {
                    e = new AD_tblUserPermission()
                    {
                        UserGroupID = ToserID,
                        FunctionID = item.FunctionID,
                        FType = item.FType,
                        FIsActive = item.FIsActive
                    };

                    dal.Repository.Add(e);

                }
            }
        }
    }
}
